package com.wjgl.action;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wjgl.domain.User;
import com.wjgl.service.UserService;

public class LoginAction extends ActionSupport {
	private UserService userService;
	private String name = null;
	private String password = null;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	@Override
	public String execute() throws Exception {
		User user = new User();
		user.setName(name);
		user.setPassword(password);
		user = userService.login(user);
		if(user != null){
			ActionContext ac = ActionContext.getContext();
			Map session = ac.getSession();
			session.put("userid", user.getId());
			session.put("username", user.getName());
			if(user.getRole() != null){
				session.put("roleid", user.getRole().getId());
				session.put("role", user.getRole().getName());
			} else{
				session.put("roleid", 0);
				session.put("role", "null");
			}
			return SUCCESS;
		}
		return INPUT;
		
	}
	
	public String logout() throws Exception {
		HttpSession session = ServletActionContext.getRequest().getSession(); 
		session.invalidate();
		return SUCCESS;
	}
	
}
